#!/bin/bash

# 检查是否为root用户
if [ "$EUID" -ne 0 ]
  then echo "请以root用户运行此脚本"
  exit
fi

# 检查系统类型
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$NAME
    VER=$VERSION_ID
else
    echo "无法确定操作系统类型"
    exit 1
fi

echo "检测到操作系统: $OS"

# 安装rclone
if [[ $OS == *"Ubuntu"* ]] || [[ $OS == *"Debian"* ]]; then
    # Ubuntu/Debian系统
    echo "正在安装rclone (Ubuntu/Debian)..."
    curl -O https://downloads.rclone.org/rclone-current-linux-amd64.zip
    unzip rclone-current-linux-amd64.zip
    cd rclone-*-linux-amd64
    sudo cp rclone /usr/bin/
    sudo chown root:root /usr/bin/rclone
    sudo chmod 755 /usr/bin/rclone
    sudo mkdir -p /usr/local/share/man/man1
    sudo cp rclone.1 /usr/local/share/man/man1/
    sudo mandb
elif [[ $OS == *"CentOS"* ]] || [[ $OS == *"Red Hat"* ]] || [[ $OS == *"Fedora"* ]]; then
    # CentOS/RHEL/Fedora系统
    echo "正在安装rclone (CentOS/RHEL/Fedora)..."
    curl -O https://downloads.rclone.org/rclone-current-linux-amd64.zip
    unzip rclone-current-linux-amd64.zip
    cd rclone-*-linux-amd64
    sudo cp rclone /usr/bin/
    sudo chown root:root /usr/bin/rclone
    sudo chmod 755 /usr/bin/rclone
    sudo mkdir -p /usr/local/share/man/man1
    sudo cp rclone.1 /usr/local/share/man/man1/
    sudo mandb
else
    echo "不支持的操作系统，请手动安装rclone"
    exit 1
fi

# 验证安装
echo "验证rclone安装..."
rclone version

if [ $? -eq 0 ]; then
    echo "rclone安装成功!"
else
    echo "rclone安装失败!"
    exit 1
fi

# 清理临时文件
cd ..
rm -rf rclone-*-linux-amd64*
echo "安装完成!"